$(function(){
	
});

$.fn.jqGridInit = function(option){
	var gridId = this[0].id;
	var pagerId = gridId+"-pager";
	
	if($("#"+gridId).length > 1){
		console.log("gridID重复:"+gridId);
		return;
	}
	if($("#"+gridId).length > 1){
		console.log("pagerId关联的翻页工具ID重复:"+gridId);
		return;
	}
	
	function enableTooltips(table) {
		$('.navtable .ui-pg-button').tooltip({container:'body'});
		$(table).find('.ui-pg-div').tooltip({container:'body'});
	}
	function updatePagerIcons(table) {
		var replacement = 
		{
			'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
			'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
			'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
			'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
		};
		$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
			var icon = $(this);
			var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
			if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
		})
	}
	
	
	$(this).after("<div id='"+pagerId+"'></div>");
	var option_default = {
        height:'auto',
        datatype : "json",
        rowNum : 10,
        rowList : [ 10, 20, 30 ],
        pager : '#'+pagerId,
        sortname : 'id',
        mtype : "post",
        viewrecords : true,
        sortable:false,
        sortorder : "desc",
        loadComplete : function() {
			var table = this;
			setTimeout(function(){
				updatePagerIcons(table);
				enableTooltips(table);
			}, 0);
		},
		altRows: true,
		multiselect: true,
        multiboxonly: true,
		subGridOptions : {
			plusicon : "ace-icon fa fa-plus center bigger-110 blue",
			minusicon  : "ace-icon fa fa-minus center bigger-110 blue",
			openicon : "ace-icon fa fa-chevron-right center orange"
		},
	};
	if(option.treeGrid){
		var tree_option = {
			treeGridModel: 'adjacency', //treeGrid模式，跟json元数据有关  
	        treedatatype:"json",
	        treeIcons:{
				plus:'ui-icon ace-icon fa fa-caret-right bigger-110 blue tree-leaf',
				minus:'ui-icon ace-icon fa fa-caret-down bigger-110 blue tree-leaf',
				leaf:'ui-icon ace-icon fa fa-circle-o bigger-110 blue'
			},
		};
		option_default = $.extend(option_default,tree_option);
	}
	option = $.extend(option_default,option);
	$("#"+gridId).jqGrid(option);
	
	if(option.autowidth){
		$(window).on('resize.jqGrid', function () {
			$("#"+gridId).jqGrid( 'setGridWidth', $("#gbox_"+gridId).parent().width());
	    })
		//resize on sidebar collapse/expand
		var parent_column = $("#"+gridId).closest('[class*="col-"]');
		$(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
			if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
				//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
				setTimeout(function() {
					$("#"+gridId).jqGrid( 'setGridWidth', parent_column.width() );
				}, 0);
				$("#"+gridId).jqGrid( 'setGridWidth',  $("#gbox_"+gridId).parent().width() );
			}
	    });
		var width = $("#"+gridId).parent().width();
		if(option.treeGrid){
			width = width-4;
		}
		$("#"+gridId).jqGrid( 'setGridWidth',  width);
	}
	if(option.treeGrid){
		$("#gbox_"+gridId).find("#organization_grid-pager_center").remove();
	}
}

$.fn.navGridInit = function(option){
	var gridId = this[0].id;
	var pagerId = gridId+"-pager";
	
	function style_search_form(form) {
		var dialog = form.closest('.ui-jqdialog');
		var buttons = dialog.find('.EditTable')
		buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
		buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
		buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
	}
	function style_search_filters(form) {
		form.find('.delete-rule').val('X');
		form.find('.add-rule').addClass('btn btn-xs btn-primary');
		form.find('.add-group').addClass('btn btn-xs btn-success');
		form.find('.delete-group').addClass('btn btn-xs btn-danger');
	}
	function style_edit_form(form) {
		//enable datepicker on "sdate" field and switches for "stock" field
		if(form.find('input[name=sdate]').datepicker){
			form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})
		}
		form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
		buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')
		
		buttons = form.next().find('.navButton a');
		buttons.find('.ui-icon').hide();
	}
	var option_default={};
	if(option){
		if(option.edit){
			option_default.edit = {
				editicon : 'ace-icon fa fa-pencil blue',
				beforeShowForm : function(e) {
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
					var ids=$("#"+gridId).jqGrid("getGridParam","selarrrow");
					style_edit_form(form);
				}
			}
			if(option.edit.beforeShowForm){
				var fn = option.edit.beforeShowForm;
				option.edit.beforeShowForm = function(e){
					fn(e);
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
					var ids=$("#"+gridId).jqGrid("getGridParam","selarrrow");
					style_edit_form(form);
				}
			}
			option.edit = $.extend(option_default.edit,option.edit);
		}
		
		if(option.add){
			option_default.add = {
				addicon : 'ace-icon fa fa-plus-circle purple',
				closeAfterAdd: true,
				recreateForm: true,
				viewPagerButtons: false,
				beforeShowForm : function(e) {
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
						.wrapInner('<div class="widget-header" />')
					style_edit_form(form);
				}
			}
			if(option.add.beforeShowForm){
				var fn = option.add.beforeShowForm;
				option.add.beforeShowForm = function(e){
					fn(e);
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
						.wrapInner('<div class="widget-header" />')
					style_edit_form(form);
				}
			}
			option.add = $.extend(option_default.add,option.add);
		}
		
		if(option.del){
			option_default.del = {
				delicon : 'ace-icon fa fa-trash-o red',
				recreateForm: true,
				beforeShowForm : function(e) {
					var form = $(e[0]);
					if(form.data('styled')) return false;
					var buttons = form.next().find('.EditButton .fm-button');
					buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
					buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
					buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>');
				}
			}
			if(option.del.beforeShowForm){
				var fn = option.add.beforeShowForm;
				option.del.beforeShowForm = function(e){
					fn(e);
					var form = $(e[0]);
					if(form.data('styled')) return false;
					var buttons = form.next().find('.EditButton .fm-button');
					buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
					buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
					buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>');
				}
			}
			option.del = $.extend(option_default.del,option.del);
		}
		
		if(option.search){
			option_default.search = {
				recreateForm: true,
				searchicon : 'ace-icon fa fa-search orange',
				afterShowSearch: function(e){
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
					style_search_form(form);
				},
				afterRedraw: function(){
					style_search_filters($(this));
				},
				multipleSearch: true
			}
			if(option.search.afterRedraw){
				var fn = option.search.afterRedraw;
				option.search.afterRedraw = function(e){
					fn(e);
					style_search_filters($(this));
				}
			}
			if(option.search.afterShowSearch){
				var fn = option.search.afterShowSearch;
				option.search.afterShowSearch = function(e){
					fn(e);
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
					style_search_form(form);
				}
			}
			option.search = $.extend(option_default.search,option.search);
		}
		
		if(option.refresh){
			option_default.refresh = {
				refreshicon : 'ace-icon fa fa-refresh green',
			}
			option.refresh = $.extend(option_default.refresh,option.refresh);
		}
		
		if(option.view){
			option_default.view = {
				//查看窗口
				recreateForm: true,
				viewicon : 'ace-icon fa fa-search-plus grey',
				beforeShowForm: function(e){
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
					//把所有列都展现出来，不管是否是hidden
					//$("#ViewTbl_grid-table tr[rowpos]").show();
					if($(".EditTable tr:first-child div[name='action_buttons']").length == 0){
						$(".EditTable tr:first-child").show();
					}
				}
			}
			if(option.view.beforeShowForm){
				var fn = option.view.beforeShowForm;
				option.view.beforeShowForm = function(e){
					fn(e);
					var form = $(e[0]);
					form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />');
					//把所有列都展现出来，不管是否是hidden
					//$("#ViewTbl_grid-table tr[rowpos]").show();
					if($(".EditTable tr:first-child div[name='action_buttons']").length == 0){
						$(".EditTable tr:first-child").show();
					}
				}
			}
			option.view = $.extend(option_default.view,option.view);
		}
		
	}
	
	/**
	 每个按钮可设置如下
	 ***************** 属性 *******************
	 editicon : 'ace-icon fa fa-pencil blue',  图标
	 width: 300,			宽度
	 hide:false,			按钮隐藏，或者直接删除掉节点
	  
	 ***************** 事件 *********************
	 beforeSubmit: function(postData, formid){  //提交前的事件
	 
	*/
	$("#"+gridId).jqGrid('navGrid',"#"+pagerId,option);
}